package com.dyna.runner;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dyna.constants.RedisKeyConstant;
import com.dyna.core.utils.SpringUtil;
import com.dyna.domain.entity.Items;
import com.dyna.mapper.ItemsMapper;
import com.dyna.utils.RdsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class OnloadRedisRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        log.info("=====>>>开始初始化数据");
        //提前加载物品数据到redis中
        ThreadUtil.execute(this::doOnloadItems);
        log.info("=====>>>初始化物品库存数据成功");
    }

    /**
     * 加载物品数据到缓存中
     */
    private void doOnloadItems() {
        //加载不为0的所有物品
        ItemsMapper itemsMapper = SpringUtil.getBean(ItemsMapper.class);
        LambdaQueryWrapper<Items> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Items::getCount, 0);
        List<Items> itemsList = itemsMapper.selectList(queryWrapper);
        Map<String, Object> map = itemsList.stream().collect(Collectors.toMap(
                item -> item.getItemId().toString(),
                Items::getCount
        ));
        map.forEach((k,v)-> {
            if (0 != Convert.toInt(v)) {
                RdsUtil.set(RedisKeyConstant.ITEM_LIST_KEY + k,v.toString());
            }
        });
    }

}
